<template>
  <PageLayout full safe-area="none" :page-style="pageStyle">
    <template #header>
      <HeaderLayout show-back title="消息中心">
        <template #action-icon>
          <TrackButton :track-id="'MessageCenter.NavigateBar.Clean.Icon'" :type="TrackType.BusinesssScene">
            <view class="all-read" hover-class="hovering" @click="readAllMessage">
              <image mode="aspectFit" src="/static/nav/Clean.png" />
            </view>
          </TrackButton>
        </template>
      </HeaderLayout>
    </template>

    <PageLayout safe-area="none">
      <!--头部导航-->
      <template #header>
        <view class="nav-tabs">
          <view class="nav-tabs-inner">
            <view class="nav-indicator" :style="{ left: `calc(${beChoosedType} * 50%)` }"></view>
            <!--家电消息-->
            <view class="tab-item appliance-message" :class="{ choosed: beChoosedType === 0 }" @click="changeType(0)">
              <view :class="{ 'has-red-badge': unReadModel.appliance }">家电消息</view>
            </view>

            <!--系统消息-->
            <view class="tab-item system-message" :class="{ choosed: beChoosedType === 1 }" @click="changeType(1)">
              <view :class="{ 'has-red-badge': unReadModel.system }">系统消息</view>
            </view>
          </view>
        </view>
      </template>

      <scroll-view class="content-view" scroll-y @scrolltolower="loadMoreData" upper-threshold="5">
        <!--暂无更多消息-->
        <view v-if="isNoData" class="no-data">
          <view class="no-data-view">
            <image :src="netconfig.ASSETS_IMGURL + 'img_message_empty.png'" class="icon" />
            <view class="text">暂无消息</view>
          </view>
        </view>
        <view v-else class="message-list safe-area-bottom">
          <!--家电消息列表-->
          <template v-if="beChoosedType === 0">
            <view
              v-for="(applianceMessage, index) in applianceMessageList"
              :key="index"
              class="message-item"
              @click="goToDetail(applianceMessage)"
            >
              <!--家电图片-->
              <alt-picture class="message-image" :src="applianceMessage.image" />
              <!--家电信息等-->
              <view class="message-content">
                <!--家电名称-->
                <view class="message-title">
                  <view class="title-text" :class="{ 'has-red-badge': applianceMessage.isRead === 0 }">
                    <text>{{ applianceMessage.name }}</text>
                  </view>
                  <image class="arrow" mode="aspectFit" src="/static/home/MessageCenterArrow.png" />
                </view>
                <!--消息描述-->
                <view class="message-detail-list">
                  <view v-for="detail in applianceMessage.list.slice(0, 3)" :key="detail.id" class="detail-item">
                    <text class="detail-content appliance_titile">{{ detail.messageContent }}</text>
                    <text class="detail-time">{{ detail.sendTimeByDateDesc }}</text>
                  </view>
                </view>
              </view>
            </view>
          </template>
          <!--系统消息列表-->
          <template v-if="beChoosedType === 1">
            <view
              class="message-item"
              v-for="(message, index) in systemMessageList"
              :key="index"
              @click="readSystemMessage(index)"
            >
              <!--信息等-->
              <view class="message-content">
                <!--标题-->
                <view class="message-title">
                  <view class="title-text" :class="{ 'has-red-badge': message.unread }">
                    <text>{{ message.messageTitle }}</text>
                  </view>
                  <view class="system-title-right">
                    <text class="detail-time system-time"
                      >{{ message.sendTimeByDateDesc }} {{ message.sendTimeByTimeDesc }}</text
                    >
                    <image
                      v-if="message.canClick"
                      class="arrow"
                      mode="aspectFit"
                      src="/static/home/MessageCenterArrow.png"
                      @click.stop="jumpToDetail(index)"
                    />
                  </view>
                </view>
                <!--消息描述-->
                <view class="message-detail-list">
                  <view class="detail-item">
                    <view class="detail-content system-content">{{ message.messageContent }}</view>
                  </view>
                </view>
              </view>
            </view>
            <view class="no-more-tips" v-if="!system_hasMore">当前没有更多消息</view>
          </template>
        </view>
      </scroll-view>
    </PageLayout>

    <NetworkError :show-flag="noNetwork" />
    <Modal
      :ok-text="$t('Navigator.Loading.Acknowledge.Text')"
      :title="$t('Navigator.Loading.Hint.Text')"
      :visible="loadStore.errorHint"
      @ok="close"
    >
      <text class="comError">{{ loadStore.errorTxt }}</text>
    </Modal>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import NetworkError from '@/common/networkError.vue'
import Modal from '@/common/modal.vue'

import netconfig from '@/config/netconfig'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { updateClickLinkStatus, readMessageRecords } from '@/api/wxuserSignInfo'
import { jumpMP, showLoading } from '@/utils/mpHelper'
import { choosePath, openArticle } from '@/utils/loading'
import { getDeviceMessageList, getSystemMessageList, readByMessageid } from '@/api/messageCenter'
import type { UnReadModel } from '@/api/messageCenter'
import type { Message } from '@/api/messageCenter'
import { useLoadStore } from '@/store/loading'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'

export type ApplianceDes = {
  des: string
  time: string
  title: string
}
export type ApplianceList = {
  type: string
  image: string
  messageLink: string
  name: string
  list: Message[]
  isRead: 0 | 1
}

type SystemInfo = {
  id: number
  haId: string
  unread: boolean
  messageTitle: string
  messageContent: string
  messageLink: string
  sendTime: string
  sendTimeByDateDesc: string
  sendTimeByTimeDesc: string
  canClick: boolean
}

const loadStore = useLoadStore()

const applianceMessageList = ref<ApplianceList[]>([])

const pageStyle = {
  backgroundColor: '#F4F4F4',
}

const i18n = useI18n()

const appliance_pageSize = 20
let appliance_currentPage = 1
const system_pageSize = 10
let system_currentPage = 1

const appliance_hasMore = ref(false)
const system_hasMore = ref(false)

let noNetwork = ref(false)
let beChoosedType = ref(0)

let systemPage = ref(1)
let haPage = ref(1)
let systemMessageList = ref<SystemInfo[]>([])
let errorHint = ref(false)
let errorTxt = ref('')
let evt = null
const isNoData = computed(() => {
  if (beChoosedType.value === 0) {
    return applianceMessageList.value.length === 0
  } else if (beChoosedType.value === 1) {
    return systemMessageList.value.length === 0
  }
  return false
})

let currentIndex = 0

const unReadModel = ref<UnReadModel>({
  appliance: false,
  system: false,
})

/**
 * 页面加载
 */
onLoad((options) => {
  if (noNetwork.value) return
  if (options?.beChoosedType) {
    const index = parseInt(options.beChoosedType)
    changeType(index)
  } else {
    getMessageRecordListInfoInterface()
  }
})

onShow(() => {
  refreshCurrentUI()
})

function close() {
  loadStore.errorHint = false
}
/**
 * 请求所有的家电消息数据并刷新页面
 */
async function getAllDeviceMessageataAndInitUI() {
  showLoading(async () => {
    const res = await getDeviceMessageList(appliance_currentPage, appliance_pageSize)

    unReadModel.value = res.data.unread
    if (applianceMessageList.value.length > 0) {
      applianceMessageList.value.splice(0, applianceMessageList.value.length)
    }
    res.data.messageByHaId.forEach((element) => {
      element.message.forEach((item) => {
        if (yearOfTimeIsEqualToThisYear(item.sendTime)) {
          item.sendTime = item.sendTime.substring(5, item.sendTime.length - 3)
        }
      })

      let applianceList: ApplianceList = {
        image: `${netconfig.PHOTO_IMAGE}${element.vib}/${element.vib}.png`,
        messageLink: '',
        name: element.name,
        list: element.message,
        isRead: element.unread === true ? 0 : 1,
        type: element.type,
      }
      applianceMessageList.value.push(applianceList)
    })
  })
}

/**
 * 请求所有的系统消息数据并刷新页面
 */
async function getAllSystemMessageAndInitUI(pullupFlag: boolean) {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  })
  if (pullupFlag) {
    system_currentPage++
  }
  var res = await getSystemMessageList(system_currentPage, system_pageSize)
  uni.hideLoading()
  if (res.code === 0) {
    if (systemMessageList.value.length > 0) {
      if (!pullupFlag) {
        systemMessageList.value.splice(0, systemMessageList.value.length)
      }

      unReadModel.value = res.data.unread
    }

    if (pullupFlag) {
      // 上拉加载
      res.data.message.forEach((element, index) => {
        if (yearOfTimeIsEqualToThisYear(element.sendTime)) {
          element.sendTime = element.sendTime.substring(5, element.sendTime.length - 3)
        }
        let options = getUrlParams(element.messageLink)
        let landing_type = parseInt(options.landing_type)
        // 是否可点击判断
        if (
          landing_type === 0 ||
          landing_type === 1 ||
          landing_type === 3 ||
          landing_type === 4 ||
          landing_type === 8 ||
          landing_type === 10
        ) {
          element.canClick = true
        }
        systemMessageList.value.push(element)
      })
    } else {
      res.data.message.forEach((element, index) => {
        if (yearOfTimeIsEqualToThisYear(element.sendTime)) {
          element.sendTime = element.sendTime.substring(5, element.sendTime.length - 3)
        }
        let options = getUrlParams(element.messageLink)
        let landing_type = parseInt(options.landing_type)
        // 是否可点击判断
        if (
          landing_type === 0 ||
          landing_type === 1 ||
          landing_type === 3 ||
          landing_type === 4 ||
          landing_type === 8 ||
          landing_type == 10
        ) {
          element.canClick = true
        }
      })
      systemMessageList.value = res.data.message
    }
    system_hasMore.value = res.data.message.length === system_pageSize
  } else {
    uni.showToast({
      title: res.msg ? res.msg : '请求失败',
    })
  }
}

/**
 * 判断时间是否是今年
 * @param timeString
 */
function yearOfTimeIsEqualToThisYear(timeString: string): boolean {
  var subTime = timeString.substring(0, 4)
  var currentDate = new Date()
  var currentYear = currentDate.getFullYear().toString()
  return subTime === currentYear
}

/**
 * 到底部刷新接口
 *
 */
function loadMoreData() {
  if (currentIndex === 0) {
    if (appliance_hasMore) {
    }
  } else {
    if (system_hasMore.value === true) {
      getAllSystemMessageAndInitUI(true)
    }
  }
}
/**
 * 全部标记为欸
 */
async function readAllMessage() {
  uni.showLoading({
    title: i18n.t('正在标记为已读...'),
    mask: true,
  })
  let res = await readMessageRecords()
  uni.hideLoading()
  if (res.code === 0) {
    // 请求成功 刷新页面
    for (let i = 0; i < systemMessageList.value.length; i++) {
      systemMessageList.value[i].unread = false
    }
    for (let i = 0; i < applianceMessageList.value.length; i++) {
      applianceMessageList.value[i].isRead = 1
    }
    unReadModel.value.appliance = false
    unReadModel.value.system = false
  } else {
    uni.showToast({
      title: res.msg ? res.msg : '标记失败',
    })
  }
}
/**
 * 切换tab栏
 * @param index
 */
async function changeType(index: number) {
  currentIndex = index
  system_currentPage = 1
  appliance_currentPage = 1
  if (index != beChoosedType.value) {
    beChoosedType.value = index
    haPage.value = 1
    systemPage.value = 1
    refreshCurrentUI()
  }
  trackEvent(
    'swtich_message_center_tab',
    { tab_name: index == 0 ? '家电消息' : '系统消息' },
    TrackType.ApplianceDetail,
    index == 0 ? 'Home.MessageCenter.Appliance.Button.Text' : 'Home.MessageCenter.System.Button.Text'
  )
}

/**
 * 刷新当前页面
 */
async function refreshCurrentUI() {
  if (currentIndex === 0) {
    // 设备消息
    await getAllDeviceMessageataAndInitUI()
  } else {
    // 系统消息
    await getAllSystemMessageAndInitUI(false)
  }
}

/**
 * 刷新顶部的tab的红点
 */
async function refreshTabRedPoint() {
  if (currentIndex === 0) {
    // 设备消息
    var res = await getDeviceMessageList(1, 20)
    unReadModel.value = res.data.unread
  } else {
    // 系统消息
    var system_res = await getSystemMessageList(1, 20)
    unReadModel.value = system_res.data.unread
  }
}

/**
 * 读单挑信息
 * @param item  该条信息内容
 * @param index 该条信息索引
 */
async function readSystemMessage(index: number) {
  let messageList = systemMessageList.value
  const { id, canClick } = messageList[index]
  safeTrack(() => {
    trackEvent(
      'before_read_single_system_message',
      { message_id: id },
      TrackType.ApplianceDetail,
      'Home.MessageCenter.System.Select'
    )
  })
  //  阅读单条消息
  let res: any = null
  try {
    res = await readByMessageid(id)
  } catch (error) {
    res = error
  } finally {
    safeTrack(() => {
      trackEvent(
        'read_single_system_message',
        { message_id: id, successOrNot: res.code == 0, error_code: res.code, response_msg: res.msg },
        TrackType.ApplianceDetail,
        'Home.MessageCenter.System.Select'
      )
    })
  }
  if (res.code === 0) {
    systemMessageList.value[index].unread = false
    refreshTabRedPoint()
  }
  if (canClick) {
    jumpToDetail(index)
  }
}
/**
 * 跳转详情页
 * @param index
 */
async function jumpToDetail(index: number) {
  uni.showLoading({
    title: i18n.t('APP.Common.Loading.Text'),
    mask: true,
  })

  let messageList = systemMessageList.value
  const { id, messageLink } = messageList[index]

  //  阅读单条消息
  let res = await readByMessageid(id)
  if (res.code === 0) {
    systemMessageList.value[index].unread = false
    refreshTabRedPoint()
  }

  await updateClickLinkStatus(id)
  const options = getUrlParams(messageLink)
  if (options.landingPage) {
    options.landingPage = decodeURIComponent(options.landingPage)
  }
  const landing_type = parseInt(options.landing_type)
  if (landing_type === 0) {
    let appid = options.miniprogram_id ? options.miniprogram_id : options.appid ? options.appid : ''
    let path = options.landingPage ? options.landingPage : options.path ? options.path : ''
    if (appid) {
      jumpMP(appid, path, {}, 'Home.MessageCenter.Message.Select.ToOtherPM')
    } else {
      errorHint.value = true
      errorTxt.value = 'appid缺失'
    }
  } else if (options.landing_type == '1') {
    choosePath(options)
  } else if (options.landing_type == '3') {
    openArticle(options.article_id)
  } else if (options.landing_type == '4') {
    let url = `/pages/discovery/recipeDetail/recipeDetail?recipeId=${options.recipe_id}`
    if (options.isDefault == '1') {
      url = `/pages/discovery/recipeDetail_1/recipeDetail?recipeId=${options.recipe_id}`
    } else if (options.isDefault == '2') {
      url = `/pages/discovery/oemRecipeDetail/oemRecipeDetail?recipeId=${options.recipe_id}`
    }
    uni.navigateTo({
      url: url,
    })
  } else if (options.landing_type == '10') {
    choosePath(options)
  } else if (options.landing_type == '8') {
    choosePath(options)
  }
  uni.hideLoading()
}

/**
 * 获取消息列表数据
 */
async function getMessageRecordListInfoInterface() {}
/**
 * 判断是否为空
 * @param obj
 */
function isEmpty(obj: unknown) {
  if (!obj || typeof obj === 'undefined') {
    return true
  } else {
    return false
  }
}
/**
 * 获取url路径后的参数
 * @param str
 */
function getUrlParams(str: string) {
  if (!str) {
    // 判断是否传入值
    return {}
  }
  if (typeof str === 'string' && str.split('?').length > 1) {
    // 判断传入值得数据类型
    str = str.replace(str.split('?')[0] + '?', '')
    let arr = str.split('&')
    let obj: Record<string, string> = {}
    for (let i = 0; i < arr.length; i++) {
      let newarr = arr[i].split('=')[0]
      let key = newarr
      let value = arr[i].replace(arr[i].split('=')[0] + '=', '')
      obj[key] = value
    }
    return obj
  } else {
    return {}
  }
}

/**进入到详情 */
function goToDetail(applianceMessageData: ApplianceList) {
  trackEvent(
    'before_read_single_appliance_message',
    {},
    TrackType.BusinesssScene,
    'Home.MessageCenter.Appliance.Select'
  )
  wx.navigateTo({
    url:
      '/pages/messagecenter/messageDetail?' +
      'applianceMessageData=' +
      encodeURIComponent(JSON.stringify(applianceMessageData)),
  })
}
</script>

<style scoped lang="less">
.nav-tabs {
  background: #e4e4e7;
  height: 64rpx;
  margin: 16rpx 32rpx;
  padding: 4rpx;
  .nav-tabs-inner {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
  }
  .tab-item {
    flex: 1;
    height: 56rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 600;
    font-size: 26rpx;
    line-height: 40rpx;
    color: #333333;
    z-index: 1;
  }
  .nav-indicator {
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    box-sizing: border-box;
    overflow: hidden;
    transition: left 0.2s ease;
    background: #ffffff;
    border: 0.5px solid rgba(0, 0, 0, 0.04);
    box-shadow: px 3px 8px rgba(0, 0, 0, 0.12), 0px 3px 1px rgba(0, 0, 0, 0.04);
    box-sizing: border-box;
  }
}

.content-view {
  height: 100%;
  box-sizing: border-box;
}

.no-data {
  width: 100%;
}

.no-more-tips {
  width: 100%;
  color: #b8bac2;
  font-size: 14px;
  text-align: center;
  margin-top: 30rpx;
  margin-bottom: 30rpx;
}

.no-data-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  .icon {
    width: 275px;
    height: 428rpx;
  }
  .text {
    font-size: 28rpx;
    margin-top: 48rpx;
    color: rgba(45, 55, 70, 1);
  }
}

.text {
  font-family: 'PingFang SC';
  font-style: normal;
  font-weight: 600;
  font-size: 26rpx;
  color: #333333;
}
// 全部已读按钮
.all-read {
  width: 40rpx;
  height: 40rpx;
  &.hovering {
    filter: opacity(0.8);
  }
  > image {
    width: 100%;
    height: 100%;
  }
}
.has-red-badge {
  display: inline-flex;
  &::after {
    content: '';
    display: block;
    margin-left: 8rpx;
    width: 8rpx;
    height: 8rpx;
    border-radius: 50%;
    background-color: var(--danger-color);
    transform: translateY(10rpx);
    flex-shrink: 0;
  }
}

// 消息列表
.message-list {
  // 需要设置底部安全区 所以单独设置padding各边属性
  padding-top: 16rpx;
  padding-left: 32rpx;
  padding-right: 32rpx;
  width: 100%;
  box-sizing: border-box;
}
.message-item {
  display: flex;
  justify-content: space-between;
  padding: 24rpx 16rpx 24rpx 24rpx;
  margin-bottom: 16rpx;
  background: #ffffff;
  .message-image {
    width: 120rpx;
    height: 120rpx;
    margin-right: 24rpx;
    flex-shrink: 0;
  }
  .message-content {
    flex: 1;
    overflow: hidden;
  }
}
.message-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title-text {
    font-weight: 500;
    font-size: 28rpx;
    line-height: 40rpx;
    color: var(--dark-color);
    word-break: break-all;
  }
  .arrow {
    width: 24rpx;
    height: 48rpx;
    margin-left: 32rpx;
  }
}

.message-detail-list {
  margin-top: 20rpx;
  .detail-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    color: rgba(var(--dark-vector), 0.6);
    + .detail-item {
      margin-top: 16rpx;
    }
  }
  .detail-content {
    font-weight: 400;
    font-size: 28rpx;
    line-height: 40rpx;
  }
  .system-content {
    display: flex;
    justify-content: right;
    align-items: center;
  }
  .appliance_titile {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .detail-time {
    flex-shrink: 0;
    font-weight: 400;
    font-size: 24rpx;
    line-height: 40rpx;
    margin-left: 16rpx;
  }
}
.system-time {
  color: #333;
  text-align: center;
  font-family: PingFang SC;
  font-size: 24rpx;
  font-style: normal;
  font-weight: 400;
  letter-spacing: -0.16rpx;
  opacity: 0.6;
}

.system-title-right {
  display: flex;
  justify-content: right;
  align-items: center;
}
</style>
